<template>
  <div>
    <div class="page-header">
      <div class="left">
        <h3 class="page-title">出版社管理</h3>
        <ul class="breadcrumb">
          <li class="breadcrumb-item">
            <router-link :to="{ path: '/' }">首页</router-link>
          </li>
          <li class="breadcrumb-item">图书管理</li>
          <li class="breadcrumb-item active">出版社列表</li>
        </ul>
      </div>
      <div class="right" title="添加课程" @click="onAdd()">
        <el-icon style="margin: 5px 0;display:block;">
          <Plus/>
        </el-icon>
      </div>
    </div>
    <transition-group
        appear
        name="animate__animated animate__bounce"
        enter-active-class="animate__fadeIn"
    >
      <el-card key="1">
        <el-form :inline="true">
          <el-form-item label="搜索">
            <el-input v-model="state.search" placeholder="请输入出版社"></el-input>
          </el-form-item>
        </el-form>
        <div class="table-container" key="1">
          <el-table
              :data="state.list.slice((pagination.currentPage-
1)*pagination.pageSize,pagination.currentPage*pagination.pageSize)"
              stripe
              style="width: 100%">
            <el-table-column
                type="index"
                prop=""
                label=""
                :index="(index)=>{ return (pagination.currentPage-
1)*pagination.pageSize + index + 1 }"
                width="50">
            </el-table-column>
            <el-table-column
                prop="publish"
                label="出版社">
            </el-table-column>
            <el-table-column
                prop=""
                label="操作"
                align="center"
                width="150">
              <template #default="scope">
                <el-button size="small" plain
                           type="primary"
                           @click="onEdit(scope.$index)">&nbsp;修改
                </el-button>
                <el-popconfirm
                    title="确定删除该数据吗？"
                    @confirm="onDelete(scope.$index)"
                >
                  <template #reference>
                    <el-button size="small" plain
                               type="danger">&nbsp;删除
                    </el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
              @current-change="handleCurrentChange"
              v-model:current-page="pagination.currentPage"
              v-model:page-size="pagination.pageSize"
              :total="pagination.total"
              layout="total,prev, pager, next">
          </el-pagination>
        </div>
        <!--注册对话框-->
        <el-dialog
            width="50%"
            v-model="state.dialogAdd.show"
            :title="state.dialogAdd.title"
            :close-on-click-modal='false'
            :close-on-press-escape='false'
            :modal-append-to-body='false'>
          <!--使用el-form组件进行数据添加和修改-->
          <el-form
              ref="myformAdd"
              :model="state.mymodel"
              :rules="rules"
              label-width="150px"
              style="margin:10px;width:auto;">
            <el-form-item label="出版社" prop="publish">
              <el-col :span="15">
                <el-input type="string" v-model="state.mymodel.publish"></el-input>
              </el-col>
            </el-form-item>
            <el-form-item class="text_right">
              <el-button type="primary" @click='onAddSave(myformAdd)'>保 存</el-button>
              <el-button @click="state.dialogAdd.show = false">取 消</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
        <!--修改信息对话框-->
        <el-dialog
            width="50%"
            v-model="state.dialogEdit.show"
            :title="state.dialogEdit.title"
            :close-on-click-modal='false'
            :close-on-press-escape='false'
            :modal-append-to-body='false'>
          <!--使用el-form组件进行数据添加和修改-->
          <el-form
              ref="myformEdit"
              :model="state.mymodel"
              :rules="rules"
              label-width="150px"
              style="margin:10px;width:auto;">
            <!--如果是修改,则账号为只读-->
            <el-form-item label="出版社" prop="publish">
              <el-col :span="15">
                <el-input type="string" v-model="state.mymodel.publish"></el-input>
              </el-col>
            </el-form-item>
            <el-form-item class="text_right">
              <el-button type="primary" @click='onEditSave(myformEdit)'>保 存</el-button>
              <el-button @click="state.dialogEdit.show = false">取 消</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </el-card>
    </transition-group>
  </div>
</template>
<script setup>
//Vue3.x 组合式API写法
import {ref, reactive, onMounted} from "vue";
import {ElMessage} from 'element-plus';
import {del, get, post, put} from "@/utils/request"
//使用一个reactive方法让状态作为响应式对象
const state = reactive({
  list: [],
  mymodel: {
    id: '',
    publish: ''
  },
  dialogAdd: {
    title: '',
    show: false,
    option: ''
  },
  dialogEdit: {
    title: '',
    show: false,
    option: ''
  },
  item: {},
  selectedIndex: -1,
})

const rules = reactive({
  publish: [
    {required: true, message: '请填写出版社', trigger: 'blur'},
  ],
})
//翻页参数对象
const pagination = reactive({
  currentPage: 1, //当前页(默认第一页)
  pageSize: 10, //每页显示条目个数
  total: state.list.length, //总条目数
})
//生命周期钩子
onMounted(async () => {
  const getUser = await get("/publish")
  state.list = getUser;
  pagination.total = state.list.length;
})
//响应注册按钮,打开注册对话框
const onAdd = () => {
//清空表单
  state.mymodel = {
    publish: '',
    id: ''
  }
//弹出注册对话框
  state.dialogAdd = {
    title: '新增出版社',
    show: true,
    option: 'add'
  }
}
//响应注册对话框保存按钮
const myformAdd = ref();
const onAddSave = async (form) => {
  if (!form) return
  await form.validate(async valid => {
    if (valid) {
      const addUser = await post("/publish", state.mymodel)
      ElMessage({
        message: "保存成功！",
        type: "success"
      });
      //跟新表格
      state.list.push(addUser);
      pagination.total = state.list.length;
      //清空表单
      state.mymodel = {
        id: '',
        publish: ''
      }
      //关闭对话框
      state.dialogAdd = {
        title: '',
        show: false,
        option: ''
      }
    }
  })
}
//响应修改按钮,打开修改对话框
const onEdit = (index) => {
//获得要修改的信息
//由于进行了翻页,传进来的index为当前页的行索引,需要转换为数组索引
  let listIndex = (pagination.currentPage - 1) * pagination.pageSize + index
  let user = state.list[listIndex];
//临时保存选中的索引
  state.selectedIndex = listIndex;
//回填数据
  state.mymodel = {
    id: user.id,
    publish: user.publish
  }
//弹出注册对话框
  state.dialogEdit = {
    title: '修改出版社信息',
    show: true,
    option: 'add'
  }
}
//响应修改对话框保存按钮
const myformEdit = ref()
const onEditSave = async (form) => {
  if (!form) return
  await form.validate(async valid => {
    if (valid) {
      const result = await put("/publish", state.mymodel)
      try {
        ElMessage({
          message: "保存成功！",
          type: "success"
        });
        //更新表格
        state.list.splice(state.selectedIndex, 1, result)
        //清空表单
        state.mymodel = {
          id: '',
          publish: ''
        }
        //重置selectedIndex
        state.selectedIndex = -1;
        //关闭对话框
        state.dialogEdit = {
          title: '',
          show: false,
          option: ''
        }
      } catch (err) {
        ElMessage({
          message: "操作失败！",
          type: "error"
        });
      }
    }
  })
}
//响应删除按钮
const onDelete = async (index) => {
//删除被选中的数据
//由于进行了翻页,传进来的index为当前页的行索引,需要转换为数组索引
  let listIndex = (pagination.currentPage - 1) * pagination.pageSize + index
  //删除
  let id = state.list[listIndex].id;
  const result = await del(`/publish/${id}`)
  if (result === 200) {
    ElMessage("删除成功");
    // 删除table起始下标为1，长度为1的一个值
    state.list.splice(listIndex, 1);
    pagination.total = state.list.length;
  }
}
//表格翻页控制方法
const handleCurrentChange = (val) => {
  pagination.currentPage = val;
}
</script>
<style scoped>
.table-container {
  text-align: right;
}
</style>
